﻿using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Web;
using System.Web.Hosting;

namespace CafeOnline.Helpers {
    [Export(typeof(DiskFileStore))]
    public class DiskFileStore {
        private string m_uploadFolder = HostingEnvironment.MapPath("~/Upload");

        /// <summary>
        /// Saves the uploaded file.
        /// </summary>
        /// <param name="fileBase">The file base.</param>
        /// <returns></returns>
        public Guid SaveUploadedFile(HttpPostedFile fileBase) {
            var identifier = Guid.NewGuid();
            fileBase.SaveAs(GetDiskLocation(identifier));
            return identifier;
        }

        public Guid SaveUploadedFile(Stream fileContent, string fileExt) {
            //Creating a FileStream to save file's content
            var identifier = Guid.NewGuid();
            using (var fileStream = File.Create(GetDiskLocation(identifier) + "." + fileExt)) {
                fileContent.Seek(0, SeekOrigin.Begin);
                fileContent.CopyTo(fileStream);
                fileStream.Dispose();
                return identifier;
            }
        }
        /// <summary>
        /// Gets the disk location.
        /// </summary>
        /// <param name="identifier">The identifier.</param>
        /// <returns></returns>
        private string GetDiskLocation(Guid identifier) {
            return Path.Combine(m_uploadFolder, identifier.ToString());
        }
    }
}